package validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import command.AdvancedSearchForm;

@Component
public class AdvancedSearchFormValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return AdvancedSearchForm.class.equals(clazz);
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		boolean ok=true;
		double min=0;
		double max=0;
		AdvancedSearchForm form = (AdvancedSearchForm) target;
		if(form.getPattern().length()>300){
			errors.rejectValue("pattern", "tooLong");
		}
		try{
			if(!(form.getMinPrice()==null))
				if((min=new Double(form.getMinPrice()))<0)
					throw new NumberFormatException();
		}catch(NumberFormatException e){
			ok=false;
			errors.rejectValue("minPrice", "illegal");
		}
		try{
			if(!(form.getMaxPrice()==null)){
				if((max=new Double(form.getMaxPrice()))<0)
					throw new NumberFormatException();
			}else{
				max=min;
			}
		}catch(NumberFormatException e){
			ok=false;
			errors.rejectValue("maxPrice", "illegal");
		}
		if(ok){
			if(min>max){
				errors.rejectValue("minPrice", "swap");
			}
		}
		
	}
}